package com.heima.user.service.impl;

import com.heima.common.constants.BehaviorConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.behavior.dtos.FollowBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.service.ApUserRelationService;
import com.heima.utils.common.thread.AppThreadLocalUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Service
@Slf4j
@RequiredArgsConstructor
public class ApUserRelationServiceImpl implements ApUserRelationService {

    //reids
    private final CacheService cacheService;

    /**
     * 关注与取消关注
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult userFollowBehavior(FollowBehaviorDto dto) {

        //1 参数校验
        if (dto.getOperation() == null || dto.getOperation() < 0 || dto.getOperation() > 1) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }


        //2.获取user
        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //当前用户id
        Integer ApUserId = user.getId();

        //被关注作者id
        Integer followUserId = dto.getAuthorId();

        //3.  0  关注   1  取消
        if(dto.getOperation()==0){

            //将对方写入当前用户的关注中
            cacheService.zAdd(BehaviorConstants.APUSER_FOLLOW_RELATION+ApUserId,followUserId.toString(),System.currentTimeMillis());

            //将当前用户写入对方的粉丝中
            cacheService.zAdd(BehaviorConstants.APUSER_FANS_RELATION+followUserId,ApUserId.toString(),System.currentTimeMillis());

            //取消关注
        }else {

            //将对方从当前用户的关注中删除
            cacheService.zRemove(BehaviorConstants.APUSER_FOLLOW_RELATION+ApUserId,followUserId.toString());

            //将当前用户从对方的粉丝中删除
            cacheService.zRemove(BehaviorConstants.APUSER_FANS_RELATION+followUserId,ApUserId.toString());

        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);

    }
}

















